package Servlets.qy;

import Bean.Product;
import Bean.StockMessage;
import Bean.StockProductInventory;
import Bean.tea_category;
import Util.GokJDBCUtil2;
import Util.RES;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


//@WebServlet(name = "StockQueryServlet", urlPatterns = {"/StockQueryServlet", "/Chaye_war/pages/stock_manage/StockQueryServlet"})
@WebServlet(name = "StockQueryServlet", urlPatterns = {"/StockQueryServlet", "/pages/stock_manage/StockQueryServlet"})

public class StockQueryServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String action = request.getParameter("action");

        if ("getCategories".equals(action)) {
            // 获取所有茶叶分类
            getCategories(out);
        } else if ("search".equals(action)) {
            // 执行搜索
            searchProducts(request, out);
        } else if ("getProductDetail".equals(action)) {
            // 获取商品详情
            getProductDetail(request, out);
        }

    }

    private void getProductDetail(HttpServletRequest request, PrintWriter out) {
        try {
            // 获取商品 ID
            String productId = request.getParameter("productId");

            String sql = "SELECT p.proname, p.price, p.originplace, p.levelid, pl.levelname, p.productionyear," +
                    "p.productionmonth FROM product p JOIN product_level pl ON p.levelid = pl.id " +
                    "WHERE p.id = ? AND p.isdeleted = 0 AND pl.isdeleted = 0";

            // 使用原生 JDBC 查询，因为我们需要自定义字段
            List<Product> products = GokJDBCUtil2.queryAll(sql.toString(), Product.class, productId);


            StockMessage<Product> msg = new StockMessage<>(products, "", "", "", "");

            out.print(RES.success(msg));

        } catch (Exception e) {
            e.printStackTrace();
            out.print("{}");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    private void getCategories(PrintWriter out) {
        try {
            String sql = "SELECT * FROM tea_category WHERE isdeleted = 0";
            List<tea_category> categories = GokJDBCUtil2.queryAll(sql, tea_category.class);

            if (categories == null) {
                categories = List.of(); // 如果查询结果为null，创建一个空列表
            }

            StringBuilder json = new StringBuilder();
            json.append("[");
            for (int i = 0; i < categories.size(); i++) {
                tea_category category = categories.get(i);
                if (i > 0) json.append(",");
                json.append("{")
                        .append("\"id\":").append(category.getId()).append(",")
                        .append("\"name\":\"").append(category.getCategoryname()).append("\"")
                        .append("}");
            }
            json.append("]");
            out.print(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
            out.print("[]"); // 出现异常时返回空数组
        }
    }

    private void searchProducts(HttpServletRequest request, PrintWriter out) {
        try {
            // 获取查询参数
            String productName = request.getParameter("productName");
            String categoryId = request.getParameter("category");
            int currentPage = Integer.parseInt(request.getParameter("currentPage") != null ? request.getParameter("currentPage") : "1");
            int pageSize = Integer.parseInt(request.getParameter("pageSize") != null ? request.getParameter("pageSize") : "5");

            StringBuilder sql = new StringBuilder();
            sql.append("SELECT p.id, p.proname, p.originplace, p.quantity, tc.categoryname ")
                    .append("FROM product p ")
                    .append("LEFT JOIN tea_category tc ON p.categoryid = tc.id ")
                    .append("WHERE p.isdeleted = 0 ");

            // 处理商品名称参数
            if (productName != null && !productName.trim().isEmpty()) {
                sql.append("AND p.proname LIKE '%").append(productName).append("%' ");
            }

            // 处理分类参数
            if (categoryId != null && !categoryId.isEmpty() && !categoryId.equals("")) {
                sql.append("AND p.categoryid = ").append(categoryId).append(" ");
            }

            sql.append("ORDER BY tc.categoryname ");

            // 计算偏移量
            int offset = (currentPage - 1) * pageSize;

            sql.append("LIMIT ").append(offset).append(", ").append(pageSize);

            // 使用原生JDBC查询，因为我们需要自定义字段
            List<StockProductInventory> products = GokJDBCUtil2.queryAll(sql.toString(), StockProductInventory.class);

            // 检查查询结果是否为null
            if (products == null) {
                products = List.of(); // 如果查询结果为null，创建一个空列表
            }

            // 查询总记录数
            StringBuilder countSql = new StringBuilder();
            countSql.append("SELECT COUNT(*) FROM product p ");
            countSql.append("LEFT JOIN tea_category tc ON p.categoryid = tc.id ");
            countSql.append("WHERE p.isdeleted = 0 ");
            if (productName != null && !productName.trim().isEmpty()) {
                countSql.append("AND p.proname LIKE '%").append(productName).append("%' ");
            }
            if (categoryId != null && !categoryId.isEmpty() && !categoryId.equals("")) {
                countSql.append("AND p.categoryid = ").append(categoryId).append(" ");
            }
            // 获取查询条件下的总记录数
            int totalCount = GokJDBCUtil2.queryForCount(countSql.toString());
            int totalPage = (int) Math.ceil((double) totalCount / pageSize);

            // 构造返回结果
            StockMessage<StockProductInventory> msg = new StockMessage<>(products, String.valueOf(totalCount), String.valueOf(totalPage), String.valueOf(currentPage), String.valueOf(pageSize));

            out.print(RES.success(msg));
        } catch (Exception e) {
            e.printStackTrace();
            // 出现异常时返回空数组
            out.print("{\"totalCount\":0, \"products\":[]}");
        }
    }
}
